bdmap.BDmap = zk.$extends(zul.Widget, {
    /**
     * anchor: 控件停靠位置(左上，右上，左下，右下)
     * offset: 控件的偏移值(x，y)
     */
    _map: null,
    _mapStyle: "",
    _areaStyle: null,
    _enableMapClick: true,
    _infobox: true,
    _zoom: 15,
    _dragging: true,
    _scrollWheelZoom: true,
    _doubleClickZoom: true,
    _pinchToZoom: true,
    _choosePoint: false,           //拖拽选点
    _scaleControl: false,          //比例尺
    _scaleAnchor: "",
    _scaleOffset: "",
    _copyrightControl: false,      //版权信息
    _copyrightAnchor: "",
    _copyrightOffset: "",
    _copyrightContent: "",
    _maptypeControl: false,        //地图类型
    _maptypeAnchor: "",
    _maptypeOffset: "",
    _maptypeStyle: "",
    _maptypeArray: "",
    _trafficControl: false,        //路况图层
    _trafficAnchor: "",
    _trafficOffset: "",
    _navigationControl: false,     //平移缩放
    _navigationAnchor: "",
    _navigationOffset: "",
    _navigationStyle: "",
    _geolocationControl: false,    //定位控件
    _geolocationAnchor: "",
    _geolocationOffset: "",
    _geolocationIcon: "",
    _autoLocation: false,
    _overviewMapControl: false, //缩略地图
    _overviewMapAnchor: "",
    _overviewMapOffset: "",
    _overviewMapSize: "",
    _drawingManager: false, //绘制工具
    _drawingMode: "",
    _drawingManagerAnchor: "",
    _drawingManagerOffset: "",
    _drawingData: null,
    _marks: null,             //覆盖物
    _markerClusterer: false,    //点聚合
    _customMarks: null,     //自定义覆盖物
    _position: null,    //目标位置
    _positionMark: null,    //位置标记、提示
    _positionMarkSize: null,
    _drivingRoute: false,
    _drivingRoutePoints: null,
    drivingZoomCtrl: null,
    drivingRouteData : {},
    markers: null,

    $define: {
        map: function (val) {
        },
        mapStyle: function () {
        },
        areaStyle: function (val) {
            if (!!this._map)
                this.drawAreaBoundary();
        },
        enableMapClick: function (val) {
        },
        infobox: function (val) {
        },
        zoom: function (val) {
            if (!(!this._map))
                this.setMapZoom();
        },
        dragging: function (val) {
        },
        scrollWheelZoom: function (val) {
        },
        doubleClickZoom: function (val) {
        },
        pinchToZoom: function (val) {
        },
        choosePoint: function (val) {
            if (!!this._map && val)
                this.showChooseIcon();
        },
        scaleControl: function (val) {
        },
        scaleAnchor: function (val) {
        },
        scaleOffset: function (val) {
        },
        copyrightControl: function (val) {
        },
        copyrightAnchor: function (val) {
        },
        copyrightOffset: function (val) {
        },
        copyrightContent: function (val) {
        },
        maptypeControl: function (val) {
        },
        maptypeAnchor: function (val) {
        },
        maptypeOffset: function (val) {
        },
        maptypeStyle: function (val) {
        },
        maptypeArray: function (val) {
        },
        trafficControl: function (val) {
        },
        trafficAnchor: function (val) {
        },
        trafficOffset: function (val) {
        },
        navigationControl: function (val) {
        },
        navigationAnchor: function (val) {
        },
        navigationOffset: function (val) {
        },
        navigationStyle: function (val) {
        },
        geolocationControl: function (val) {
        },
        geolocationAnchor: function (val) {
        },
        geolocationOffset: function (val) {
        },
        geolocationStyle: function (val) {
        },
        autoLocation: function (val) {
            if (!(!this._map))
                this.geoLocation();
        },
        overviewMapControl: function (val) {
        },
        overviewMapAnchor: function (val) {
        },
        overviewMapOffset: function (val) {
        },
        overviewMapSize: function (val) {
        },
        drawingManager: function (val) {
        },
        drawingMode: function (val) {
        },
        drawingManagerAnchor: function (val) {
        },
        drawingManagerOffset: function (val) {
        },
        drawingData: function (val) {
            if (!(!this._map))
                this.showDrawing();
        },
        marks: function (val) {
            if (!(!this._map))
                this.showMarkers();
        },
        markerClusterer: function(val){},
        customMarks: function(val) {
            if (!(!this._map))
                this.showCustomMarks();
        },
        position: function (val) {
            if (!(!this._map)){
                if (!(!val)) {
                    if (val.indexOf(',') > -1) {
                        this.goPosition(val);
                    }else {
                        var that = this;
                        var geoc = new BMap.Geocoder();
                        geoc.getPoint(val,function (r) {
                            that.goPosition(r.lng+','+r.lat);
                        })
                    }
                }
            }
        },
        positionMark: function (v) {
        },
        positionMarkSize: function (v) {
        },
        drivingRoute: function (v) {
            if (!(!this._map)){
                if (v){
                    this._map.addControl(this.drivingZoomCtrl);
                }else {
                    this._map.removeControl(this.drivingZoomCtrl);
                }
            }
        },
        drivingRoutePoints: function (v) {
            if (!(!this._map)){
                try {
                    var point = v;
                    if (point.length < 4){
                        return;
                    }else if (point.length === 4){
                        this.drivingSearch(new BMap.Point(point[0],point[1]),new BMap.Point(point[2],point[3]),null);
                    }else {
                        this.drivingSearch(new BMap.Point(point[0],point[1]),new BMap.Point(point[2],point[3]),point[4]);
                    }
                }catch (e) {
                    console.log(e);
                    return e;
                }
            }
        }
    },

    redraw: function (out) {
        out.push('<div ', this.domAttrs_(), ' id="', this.uuid, '" /><div style="display: ', this._choosePoint?'block':'none' ,'"><img src="', zk.ajaxURI("/web/js/bdmap/img/locationicon.png", {au: true}) ,'" style="position: absolute;width: 28px;height: 28px;top: 50%;left: 50%;margin-top: -25px;margin-left: -15px"></div>');
    },

    domAttrs_: function () {
        var attr = this.$supers('domAttrs_', arguments);
        attr += ' style="height:100%;"';
        return attr;
    },

    bind_: function () {
        this.$supers(bdmap.BDmap, 'bind_', arguments);
        this._init()
    },

    unbind_: function () {
        this.$supers(bdmap.BDmap, 'unbind_', arguments);
    },

    doClick_: function () {
    },

    _init: function () {
        window.BMAP_PROTOCOL = "https";
        window.HOST_TYPE = "2";
        var that = this;

        jq.getScript("//api.map.baidu.com/getscript?v=2.0&ak=ff3g4LVAVLgDtyxgLMWh9CVU5KdTHI4t&services=&t=20200327103013").done(function () {
            that._map = new BMap.Map(that.uuid, {enableMapClick: that._infobox});
            if (!that._map)
                return;
            var bmap = that._map;
            bmap.enableScrollWheelZoom();
            let centerPoint = new BMap.Point(116.404, 39.915); //地图中心点，默认故宫
            if (!!that._position) {
                if (that._position.indexOf(',') > -1) {
                    centerPoint = new BMap.Point(that._position.split(",")[0], that._position.split(",")[1]);
                    bmap.centerAndZoom(centerPoint, that._zoom);
                }else {
                    var geocoder = new BMap.Geocoder();
                    geocoder.getPoint(that._position,function (r) {
                        centerPoint = new BMap.Point(r.lng, r.lat);
                        bmap.centerAndZoom(centerPoint, that._zoom);
                    })
                }
            } else {
                bmap.centerAndZoom(centerPoint, that._zoom);
            }

            //点击事件
            bmap.addEventListener("click", function (e) {
                var self = that;
                var geoc = new BMap.Geocoder();
                geoc.getLocation(e.point, function (res) {
                    var point = {lng: e.point.lng, lat: e.point.lat, address: res.address};
                    self.doClick_ = function(){
                        that.fire("onClick",point);
                    };

                    if (self._drivingRoute && bmap.getDefaultCursor() === "crosshair") {
                        if (typeof self.drivingRouteData.start === "undefined") {
                            self.drivingRouteData.start = point;
                            let mapicon = new BMap.Icon("//api.map.baidu.com/images/dest_markers.png", new BMap.Size(42, 34));
                            mapicon.setAnchor(new BMap.Size(14, 32));
                            bmap.addOverlay(new BMap.Marker(new BMap.Point(self.drivingRouteData.start.lng, self.drivingRouteData.start.lat), {icon: mapicon}));
                        } else {
                            self.drivingRouteData.end = point;
                            bmap.clearOverlays();
                            bmap.setDefaultCursor("pointer");
                            that.drivingSearch(new BMap.Point(self.drivingRouteData.start.lng, self.drivingRouteData.start.lat), new BMap.Point(self.drivingRouteData.end.lng, self.drivingRouteData.end.lat),null);
                        }
                    }
                });
            });

            //缩放事件
            bmap.addEventListener('zoomend', function(e) {
                if (!!that._customMarks) {
                    bmap.clearOverlays();
                    that.showCustomMarks();
                }
            });

            //拖拽事件
            bmap.addEventListener('dragend', function(e) {
                if (!!that._customMarks) {
                    that.showCustomMarks();
                }
            });

            if (!that._enableMapClick) {
                bmap.disableDragging();
                bmap.disableScrollWheelZoom();
                bmap.disableDoubleClickZoom();
                bmap.disablePinchToZoom();
            }

            if (!!that._mapStyle) {
                if (typeof that._mapStyle !== "object")
                    that._mapStyle = JSON.parse(that._mapStyle);
                bmap.setMapStyle(that._mapStyle);
            }

            if (!!that._areaStyle){
                that.drawAreaBoundary();
            }

            //目标位置
            if (!(!that._position)) {
                if (that._position.indexOf(',') > -1) {
                    that.goPosition(that._position);
                }else {
                    var geoc = new BMap.Geocoder();
                    geoc.getPoint(that._position,function (r) {
                        that.goPosition(r.lng+','+r.lat);
                    })
                }
            }

            //路线规划工具
            let self = that;
            that.ZoomControl.prototype = new BMap.Control();
            that.ZoomControl.prototype.initialize = function (bmap) {
                let wgt = self;
                // 创建DOM元素
                var div = document.createElement("div");
                var span = document.createElement("span");
                var span2 = document.createElement("span");
                span.appendChild(document.createTextNode("规划路线"));
                span2.appendChild(document.createTextNode("保存"));
                div.appendChild(span);
                div.appendChild(span2);
                // 设置样式
                span.style.padding = "0 10px";
                span2.style.padding = "0 10px";
                span2.style.borderLeft = "1px solid #999";
                div.style.cursor = "pointer";
                div.style.fontSize = "13px";
                div.style.lineHeight = "30px";
                div.style.borderRadius = "2px";
                div.style.boxShadow = "1px 1px 3px #999";
                div.style.backgroundColor = "white";
                // 绑定事件
                span.onclick = function (e) {
                    bmap.clearOverlays();
                    wgt.drivingRouteData = {};
                    bmap.setDefaultCursor("crosshair");
                };
                // 绑定事件,保存所有覆盖物

                span2.onclick = function (e) {
                    bmap.addOverlay(new BMap.Marker(new BMap.Point(wgt.drivingRouteData.start.lng,wgt.drivingRouteData.start.lat)));
                    if (typeof wgt.drivingRouteData.data !== "undefined")
                        that.fire("onSave", {data: wgt.drivingRouteData});
                    wgt.drivingRouteData = {};
                };
                // 添加DOM元素到地图中
                bmap.getContainer().appendChild(div);
                return div;
            };
            // 创建控件
            that.drivingZoomCtrl = new that.ZoomControl();
            // 添加到地图当中
            if (that._drivingRoute) {
                bmap.addControl(that.drivingZoomCtrl);
            }

            //加载规划路线
            if (!(!that._drivingRoutePoints)) {
                try {
                    var point = that._drivingRoutePoints;
                    if (point.length < 4){
                        return;
                    }else if (point.length === 4){
                        that.drivingSearch(new BMap.Point(point[0],point[1]),new BMap.Point(point[2],point[3]),null);
                    }else {
                        that.drivingSearch(new BMap.Point(point[0],point[1]),new BMap.Point(point[2],point[3]),point[4]);
                    }
                }catch (e) {
                    console.log(e);
                    return e;
                }
            }

            // 获取当前定位
            if (that._autoLocation) {
                if (that._position == null || that._position === "")
                    that.geoLocation();
            }

            //地图选点
            if (that._choosePoint) {
                that.showChooseIcon();
            }

            // 比例尺
            if (that._scaleControl) {
                var scale = new BMap.ScaleControl();
                bmap.addControl(scale);
                if (that._scaleAnchor !== "") {
                    scale.setAnchor(that.getAnchor(that._scaleAnchor));
                }
                if (that._scaleOffset !== "") {
                    scale.setOffset(that.getOffset(that._scaleOffset));
                }
            }
            // 版权
            if (that._copyrightControl) {
                var copyright = new BMap.CopyrightControl();
                bmap.addControl(copyright);
                if (that._copyrightAnchor !== "") {
                    copyright.setAnchor(that.getAnchor(that._copyrightAnchor));
                }
                if (that._copyrightOffset !== "") {
                    copyright.setOffset(that.getOffset(that._copyrightOffset));
                }
                if (that._copyrightContent) {
                    let bounds = bmap.getBounds();
                    copyright.addCopyright({id: 2020, content: that._copyrightContent, bounds: bounds})
                }
            }
            // 路况信息
            if (that._trafficControl) {
                jq.getScript('//api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.js').done(function () {
                    var traffic = new BMapLib.TrafficControl();
                    bmap.addControl(traffic);
                    if (that._trafficAnchor !== "")
                        traffic.setAnchor(that.getAnchor(that._trafficAnchor));
                    if (that._trafficOffset !== "")
                        traffic.setOffset(that.getOffset(that._trafficOffset));
                })
            }
            // 平移缩放控件
            if (that._navigationControl) {
                let parm = {};
                if (that._navigationStyle !== "")
                    parm.type = that.getNavigationType(that._navigationStyle);
                if (that._navigationAnchor !== "")
                    parm.anchor = that.getAnchor(that._navigationAnchor);
                if (that._navigationOffset !== "")
                    parm.offset = that.getOffset(that._navigationOffset);
                bmap.addControl(new BMap.NavigationControl(parm));
            }
            // 定位控件
            if (that._geolocationControl) {
                var geoCtrl = new BMap.GeolocationControl();
                bmap.addControl(geoCtrl);
                // geoCtrl.setShowAddressBar(false);
                if (that._geolocationAnchor !== "")
                    geoCtrl.setAnchor(that.getAnchor(that._geolocationAnchor));
                if (that._geolocationOffset !== "")
                    geoCtrl.setOffset(that.getOffset(that._geolocationOffset));
                if (that._autoLocation !== "")
                // geoCtrl.enableAutoLocation(true);
                    if (that._geolocationIcon !== "")
                        geoCtrl.setLocationIcon();
                geoCtrl.addEventListener("locationSuccess", function (e) {
                    console.log(e)
                });
            }
            // 地图类型
            if (that._maptypeControl) {
                let parm = {};
                if (that._maptypeStyle !== "")
                    parm.type = that.getMapType(that._maptypeStyle);
                if (that._maptypeArray !== "")
                    parm.mapTypes = that.getMapArray(that._maptypeArray);
                var maptype = new BMap.MapTypeControl(parm);
                bmap.addControl(maptype);
                if (that._maptypeAnchor !== "")
                    maptype.setAnchor(that.getAnchor(that._maptypeAnchor));
                if (that._maptypeOffset !== "")
                    maptype.setOffset(that.getOffset(that._maptypeOffset));
            }
            // 缩略地图
            if (that._overviewMapControl) {
                var overviewMap = new BMap.OverviewMapControl();
                bmap.addControl(overviewMap);
                if (that._overviewMapAnchor !== "")
                    overviewMap.setAnchor(that.getAnchor(that._overviewMapAnchor));
                if (that._overviewMapOffset !== "")
                    overviewMap.setOffset(that.getOffset(that._overviewMapOffset));
                if (that._overviewMapSize !== "")
                    overviewMap.setSize(that.getOffset(that._overviewMapSize));
            }

            // 初始化覆盖物
            if (!(!that._marks)) {
                that.showMarkers();
            }

            // 自定义覆盖物
            if (!!that._customMarks)
                that.showCustomMarks();

            // 加载规划区域
            if (!!that._drawingData)
                that.showDrawing();

            // 鼠标绘制工具
            var drawingManager = null;
            var overlays = [];
            var drawArr = [];
            if (that._drawingManager) {
                jq.getScript('//api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js').done(function () {
                    var overlaycomplete = function (e) {
                        overlays.push(e.overlay);
                        let path = e.overlay.getPath();
                        for (let i = 0; i < path.length; i++) {
                            drawArr.push({lng: path[i].lng,lat: path[i].lat});
                        }
                        console.log(drawArr);
                    };
                    var toolOptions = {};
                    toolOptions.scale = 1;
                    if (!!that._drawingMode)
                        toolOptions.drawingModes = that.getModes(that._drawingMode);
                    if (that._drawingManagerAnchor !== "") {
                        toolOptions.Anchor = that.getAnchor(that._drawingManagerAnchor);
                    }
                    if (that._drawingManagerOffset !== "") {
                        toolOptions.offset = that.getOffset(that._drawingManagerOffset);
                    }
                    var styleOptions = {
                        strokeColor: "red",    //边线颜色。
                        fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                        strokeWeight: 3,       //边线的宽度，以像素为单位。
                        strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
                        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
                        strokeStyle: 'solid'   //边线的样式，solid或dashed。
                    };
                    drawingManager = new BMapLib.DrawingManager(bmap, {
                        isOpen: false, //是否开启绘制模式
                        enableDrawingTool: true, //是否显示工具栏
                        drawingToolOptions: toolOptions,
                        circleOptions: styleOptions, //圆的样式
                        polylineOptions: styleOptions, //线的样式
                        polygonOptions: styleOptions, //多边形的样式
                        rectangleOptions: styleOptions //矩形的样式
                    });
                    //绘制工具按钮点击事件
                    var tools = document.getElementsByClassName('BMapLib_box');
                    for (let i = 1; i < tools.length; i++) {
                        tools[i].addEventListener('click', e=>{
                            bmap.clearOverlays();
                        });
                    }

                    //添加鼠标绘制工具监听事件，用于获取绘制结果
                    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
                })
            }

            // 鼠标绘制工具附属控件（撤销/保存）
            if (that._drawingManager) {
                that.ZoomControl.prototype = new BMap.Control();
                that.ZoomControl.prototype.initialize = function (bmap) {
                    var _self = that;
                    // 创建DOM元素
                    var div = document.createElement("div");
                    var span = document.createElement("span");
                    var span2 = document.createElement("span");
                    span.appendChild(document.createTextNode("撤销"));
                    span2.appendChild(document.createTextNode("保存"));
                    div.appendChild(span);
                    div.appendChild(span2);
                    // 设置样式
                    span.style.padding = "0 10px";
                    span2.style.padding = "0 10px";
                    span2.style.borderLeft = "1px solid #999";
                    div.style.cursor = "pointer";
                    div.style.fontSize = "13px";
                    div.style.lineHeight = "30px";
                    div.style.borderRadius = "2px";
                    div.style.boxShadow = "1px 1px 3px #999";
                    div.style.backgroundColor = "white";
                    div.style.marginTop = "60px";
                    // 绑定事件,撤销最后一个覆盖物
                    span.onclick = function (e) {
                        if (overlays.length > 0) {
                            let last = overlays[overlays.length - 1];
                            bmap.removeOverlay(last);
                            overlays.pop();
                            drawArr.splice(drawArr.length - last.zo.length);
                        }
                    };
                    // 绑定事件,保存所有覆盖物
                    span2.onclick = function (e) {
                        // for (let i = 0; i < overlays.length; i++) {
                        //     bdmap.removeOverlay(overlays[i]);
                        // }
                        if (drawArr.length > 0)
                            that.fire("onSave", {data: drawArr});

                        drawArr = [];
                    };
                    // 添加DOM元素到地图中
                    bmap.getContainer().appendChild(div);
                    return div;
                };
                // 创建控件
                var myZoomCtrl = new that.ZoomControl();
                if (that._drawingManagerAnchor !== "") {
                    myZoomCtrl.setAnchor(that.getAnchor(that._drawingManagerAnchor));
                }
                if (that._drawingManagerOffset !== "") {
                    myZoomCtrl.setOffset(that.getZoomOffset(that._drawingManagerOffset));
                }
                // 添加到地图当中
                bmap.addControl(myZoomCtrl);
            }
        });
    },

    /**
     * 渲染规划路线
     * @param type 路线类型（驾车：driving，公交：transit，步行：walking，骑行：riding *V2.0不支持骑行规划）
     * @param startPoint  起点（坐标或地点名称）  坐标：经度,纬度
     * @param endPoint    终点（坐标或地点名称）  坐标：经度,纬度
     */
    showRouting: function(type,startPoint,endPoint) {
        if (startPoint.indexOf(',')>-1)
            startPoint = this.getPoint(startPoint);
        if (endPoint.indexOf(',')>-1)
            endPoint = this.getPoint(endPoint);
        var routing = null;
        var onRoutingComplete = function (res) {
            if (routing.getStatus() !== BMAP_STATUS_SUCCESS){
                return ;
            }
            var plan  = res.getPlan(0);
            var tips = "耗时："+plan.getDuration(true)+" 路程："+plan.getDistance(true);
            console.log(tips);
        };
        if (type === 'driving')
            routing = new BMap.DrivingRoute(this._map, {renderOptions: {map: this._map, panel: "r-result", autoViewport: true},onSearchComplete: onRoutingComplete});
        else if (type === 'transit')
            routing = new BMap.TransitRoute(this._map, {renderOptions: {map: this._map, panel: "r-result", autoViewport: true},onSearchComplete: onRoutingComplete});
        else if (type === 'walking')
            routing = new BMap.WalkingRoute(this._map, {renderOptions: {map: this._map, panel: "r-result", autoViewport: true},onSearchComplete: onRoutingComplete});
        else if (type === 'riding')
            routing = new BMap.RidingRoute(this._map, {renderOptions: {map: this._map, panel: "r-result", autoViewport: true},onSearchComplete: onRoutingComplete});
        this._map.clearOverlays();
        routing.search(startPoint,endPoint);
    },

    search: function(name) {
        let self = this;
        var local = null;
        var options = {
            onSearchComplete: function(results){
                // 判断状态是否正确
                if (local.getStatus() === BMAP_STATUS_SUCCESS){
                    self.fire("onSearch", {pois: results.Hr});
                }
            }
        };
        local = new BMap.LocalSearch(this._map, options);
        local.search(name);
    },

    clearOverlays: function() {
        if (!!this._map)
            this._map.clearOverlays();
    },

    geoLocation: function () {
        let self = this;
        var showPosition = function(position) {
            let lat = position.coords.latitude;
            let lng = position.coords.longitude;
            const pointBak = new BMap.Point(lng, lat);
            const convertor = new BMap.Convertor();
            convertor.translate([pointBak], 1, 5,function(resPoint) {
                if(resPoint && resPoint.points && resPoint.points.length>0){
                    lng = resPoint.points[0].lng;
                    lat = resPoint.points[0].lat;
                }
                let point = new BMap.Point(lng, lat);
                self._map.addOverlay(new BMap.Marker(point));
                self._map.panTo(point);
                self._position = point;
                const geo = new BMap.Geocoder();
                geo.getLocation(point, (result) => {
                    self.fire("onLocation", {point: point, address: result.address, business: result.business, surroundingPois: result.surroundingPois});
                });
            });
        };
        var showError = function(error) {
            bmapLocation();
        };

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            bmapLocation();
        }

        function bmapLocation() {
            let geolocation = new BMap.Geolocation();
            geolocation.enableSDKLocation();
            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() === BMAP_STATUS_SUCCESS) {
                    self._map.addOverlay(new BMap.Marker(r.point));
                    self._map.panTo(r.point);
                    self._position = r.point;
                    var geocoder = new BMap.Geocoder();
                    geocoder.getLocation(r.point, function (result, error) {
                        if (result) {
                            self.fire("onLocation", {point: r.point, address: result.address, business: result.business, surroundingPois: result.surroundingPois});
                        }
                    });
                }
            });
        }
        self._autoLocation = null;
    },

    //中央显示大头针，绑定拖拽选点事件
    showChooseIcon: function() {
        let self = this;
        var dragEnd = function(e) {
            let centerPoint = self._map.getCenter();
            let geocoder = new BMap.Geocoder();
            geocoder.getLocation(centerPoint, (result, error) => {
                if (result) {
                    self._map.clearOverlays();
                    // self._map.addOverlay(new BMap.Marker(centerPoint));
                    self.fire("onLocation", {point: centerPoint, address: result.address, business: result.business, surroundingPois: result.surroundingPois});
                }
            })
        };
        this._map.addEventListener("dragend", dragEnd);
    },

    //加载区域覆盖物
    drawAreaBoundary: function() {
        var that = this;
        for (let i = 0; i < this._areaStyle.length; i++) {
            var boundary = new BMap.Boundary();
            boundary.get((this._areaStyle[i].split('-'))[0], function (rs) {
                var boundArr = rs.boundaries;
                for (let j = 0; j < boundArr.length; j++) {
                    var polygon = new BMap.Polygon(boundArr[j], {fillColor: (that._areaStyle[i].split('-'))[1],fillOpacity: 0.2,strokeColor: '#008a45',strokeWeight: 2,strokeOpacity: 0.2});
                    that._map.addOverlay(polygon);
                }
            });
        }
    },

    //驾车规划
    drivingSearch: function (start, end, pass) {
        var self = this;
        // var routePolicy = BMAP_DRIVING_POLICY_LEAST_DISTANCE;
        var drivingRoute = new BMap.DrivingRoute(this._map, {
            renderOptions: {map: this._map, autoViewport: true},
            // policy: routePolicy,
            onSearchComplete: function (res) {
                var t = res.getPlan(0);
                var tt = t.getRoute(0).getPath();
                self.drivingRouteData.data = tt;
                // console.log(tt)
            }
        });
        this._map.clearOverlays();
        if (!pass)
            drivingRoute.search(start, end);
        else {
            var waypoints = [];
            if (typeof(pass) !== "object")
                pass = JSON.parse(pass);
            for (let i = 0; i < pass.length; i++) {
                waypoints.push(new BMap.Point(pass[i].lng, pass[i].lat));
            }
            drivingRoute.search(start, end, {waypoints: waypoints});
        }
    },

    //点聚合
    showMarkers: function () {
        var that = this;
        jq.getScript("//api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js").done(function () {
            jq.getScript(zk.ajaxURI("/web/js/bdmap/js/MarkerClusterer_min.js", {au: true})).done(function () {
                // jq.getScript("//api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js").done(function () {
                try {
                    that.markers = [];
                    // if (!(!that.markerClusterer))
                    //     that.markerClusterer.clearMarkers(that.markers);
                    for (let i = 0; i < that._marks.length; i++) {
                        let marker = new BMap.Marker(new BMap.Point(that._marks[i][0], that._marks[i][1]));
                        if (!!that._marks[i][3]) {
                            let iconsize = "20,20";
                            if (!!that._marks[i][4])
                                iconsize = that._marks[i][4];
                            let markicon = new BMap.Icon(that._marks[i][3], that.getOffset(iconsize));
                            markicon.setImageSize(that.getOffset(iconsize));
                            marker = new BMap.Marker(new BMap.Point(that._marks[i][0], that._marks[i][1]), {icon: markicon});
                        }
                        if (!(!that._marks[i][2])) {
                            that.addClickHandler(marker, that._marks[i][2]);
                        }
                        let _self = that;
                        marker.addEventListener("dblclick",function(){
                            _self._map.centerAndZoom(new BMap.Point(that._marks[i][0], that._marks[i][1]), 18);
                        });
                        let iconmarker = null;
                        if (!!that._marks[i][5]){
                            let size = "100,100";
                            if (!!that._marks[i][6])
                                size = that._marks[i][6];
                            let mapicon = new BMap.Icon(that._marks[i][5], that.getOffset(size));
                            mapicon.setImageSize(that.getOffset(size));
                            iconmarker = new BMap.Marker(new BMap.Point(that._marks[i][0], that._marks[i][1]),{icon: mapicon});
                        }

                        if (that._markerClusterer) {
                            that.markers.push(marker);
                        }else {
                            that._map.addOverlay(iconmarker);
                            that._map.addOverlay(marker);
                        }
                    }
                    if (that._markerClusterer)
                        var markerClusterer = new BMapLib.MarkerClusterer(that._map, {markers: that.markers});
                    //that.markerClusterer.setStyles([{url: 'http://api.map.baidu.com/library/TextIconOverlay/1.2/src/images/m0.png',size: new BMap.Size(50,50),opt_anchor: [32, 0],textColor: '#fff',opt_textSize: 14}]);
                } catch (e) {
                    console.log(e);
                    return e;
                }
            })
        })
    },

    //渲染自定义覆盖物
    showCustomMarks: function (){
        if (Array.isArray(this._customMarks)){
            var that = this;
            jq.getScript("//api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js").done(function () {
                var overlays = that._map.getOverlays();
                for (let i = 0; i < that._customMarks.length; i++) {
                    if (that._customMarks[i][0].indexOf("-") > 0) {
                        let zoomArr = that._customMarks[i][0].split("-");
                        if (zoomArr[0] <= that._map.getZoom() && that._map.getZoom() <= zoomArr[1]) {
                            if (BMapLib.GeoUtils.isPointInPolygon(new BMap.Point(that._customMarks[i][1], that._customMarks[i][2]), that.getMapPolygon())) {
                                let flag = null;
                                for (let j = 0; j < overlays.length; j++) {
                                    if (overlays[j].point != null && overlays[j].point.lng === that._customMarks[i][1] && overlays[j].point.lat === that._customMarks[i][2])
                                        flag = true;
                                }
                                //判断地图是否已存在该覆盖物
                                if (!flag)
                                    that.drawCustomOverlay(that._customMarks[i]);
                            }
                        }
                    }
                }
            })
        }
    },

    // 添加单个自定义覆盖物
    drawCustomOverlay: function (markData) {
        var map = this._map;
        var myLabel = new BMap.Label(markData[3]);
        myLabel.setPosition(new BMap.Point(markData[1], markData[2]));
        myLabel.setStyle({border: 0, zIndex: 2, backgroundColor: "none"});
        if (!!markData[4]) {
            if (markData[4].indexOf(",") > 0) {
                var offset = markData[4].split(",");
                myLabel.setOffset(new BMap.Size(Number(offset[0]), Number(offset[1])));
            }
        }
        myLabel.addEventListener("click", function () {
            map.centerAndZoom(myLabel.getPosition(), map.getZoom() + 2);
            // map.setZoom(map.getZoom() + 2);
            // map.panTo(myLabel.getPosition());
        });
        map.addOverlay(myLabel);
    },

    /**
     * 获取地图可视区域
     * @returns {BMap.Polygon}
     */
    getMapPolygon: function(){
        var bounds = this._map.getBounds();                  //获取地图可视区域
        var sw = bounds.getSouthWest();                      //获取西南角的经纬度(左下端点)
        var ne = bounds.getNorthEast();                      //获取东北角的经纬度(右上端点)
        var wn = new BMap.Point(sw.lng, ne.lat);             //获取西北角的经纬度(左上端点)
        var es = new BMap.Point(ne.lng, sw.lat);             //获取东南角的经纬度(右下端点)

        var polygon = new BMap.Polygon([
            new BMap.Point(sw.lng,sw.lat),//左下
            new BMap.Point(wn.lng,wn.lat),//左上
            new BMap.Point(ne.lng,ne.lat),//右上
            new BMap.Point(es.lng,es.lat)//右下
        ], {strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
        return polygon;
    },

    /**
     * 获得图形的中心点
     */
    getCenterPoint: function (path) {
        var x = 0.0;
        var y = 0.0;
        for (var i = 0; i < path.length; i++) {
            x = x + parseFloat(path[i].lng);
            y = y + parseFloat(path[i].lat);
        }
        x = x / path.length;
        y = y / path.length;
        return new BMap.Point(x, y);
    },

    showDrawing: function () {
        var that = this;
        if (!!this._drawingData){
            if (this._drawingMode.toUpperCase() === "POLYGON"){
                for (let i = 0; i < this._drawingData.length; i++) {
                    var pointArr = [];
                    if (typeof(this._drawingData[i][1]) !== "object")
                        this._drawingData[i][1] = JSON.parse(this._drawingData[i][1]);
                    for (let j = 0; j < this._drawingData[i][1].length; j++) {
                        pointArr.push(new BMap.Point(this._drawingData[i][1][j].lng,this._drawingData[i][1][j].lat));
                    }

                    //标题
                    var fontColor = "#fff"; //默认白色
                    if (!!this._drawingData[i][2])
                        fontColor = this._drawingData[i][2];
                    var label = new BMap.Label('<span class="DrawingLabel" style="display:block;text-align:center;transform:scale('+Math.pow(that._map.getZoom()/15,4)+')">'+this._drawingData[i][0]+'</span>',{position:this.getCenterPoint(this._drawingData[i][1]),offset:new BMap.Size(-40,-25)});
                    label.setStyle({fontSize: "15px",fontWeight: "bold",border: "0",color: fontColor,backgroundColor: "0.0000000000001"});
                    this._map.addOverlay(label);

                    //图标
                    if (!!this._drawingData[i][4]) {
                        var icon = new BMap.Icon(this._drawingData[i][4], new BMap.Size(20, 20));
                        icon.setImageSize(new BMap.Size(20, 20));
                        var iconMarker = new BMap.Marker(this.getCenterPoint(this._drawingData[i][1]), {icon: icon});
                        iconMarker.setOffset(new BMap.Size(-3, 30));
                        this._map.addOverlay(iconMarker);
                    }

                    //区域多边形
                    var fillColor = "red"; //填充默认红色
                    if (!!this._drawingData[i][3])
                        fillColor = this._drawingData[i][3];
                    this._map.addOverlay(new BMap.Polygon(pointArr,{
                        strokeColor: fillColor,
                        fillColor: fillColor,
                        strokeWeight: 3,
                        strokeOpacity: 0.8,
                        fillOpacity: 0.6,
                        strokeStyle: 'solid'}));

                    this._map.centerAndZoom(this.getCenterPoint(this._drawingData[i][1]), this._zoom);

                    //监听地图缩放
                    this._map.addEventListener("zoomend",function(e){
                        var bmaplabel = document.getElementsByClassName('DrawingLabel');
                        for (let j = 0; j < bmaplabel.length; j++) {
                            bmaplabel[j].style.transform = "scale("+Math.pow(that._map.getZoom()/15,4)+")";
                        }
                    })
                }
            }
        }
    },

    /**
     * 检查点是否在区域（多区域）
     * @param point
     * @param polygon
     */
    checkPoint: function (point, polygon) {
        jq.getScript("//api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js").done(function () {
            if (typeof(point) !== "object") {
                point = JSON.parse(point);
            }
            if (typeof(polygon) !== "object") {
                polygon = JSON.parse(polygon);
            }
            var pt = new BMap.Point(point.lng,point.lat);
            for (let i = 0; i < polygon.length; i++) {
                var pointArr = [];
                var data = polygon[i][1];
                for (let j = 0; j < data.length; j++) {
                    pointArr.push(new BMap.Point(data[j].lng,data[j].lat));
                }
                var poly = new BMap.Polygon(pointArr);
                if (BMapLib.GeoUtils.isPointInPolygon(pt, poly)) {
                    return polygon[i][0];
                    break;
                }
            }
            return null;
        })
    },

    setMapZoom: function () {
        this._map.setZoom(this._zoom);
    },

    getPoint: function (pointstr) {
        var temp = pointstr.split(',');
        return new BMap.Point(temp[0], temp[1]);
    },

    goPosition: function (p) {
        let point = this.getPoint(p);
        if (!(!this._positionMark)) {
            let icon_mk = null;
            if (this._positionMark === "default") {
                icon_mk = new BMap.Marker(point);
            } else {
                if (!this._positionMarkSize)
                    this._positionMarkSize = "100,100";
                let mapicon = new BMap.Icon(this._positionMark, this.getOffset(this._positionMarkSize));
                mapicon.setImageSize(this.getOffset(this._positionMarkSize));
                icon_mk = new BMap.Marker(point, {icon: mapicon});
            }
            this._map.addOverlay(icon_mk);
        }
        // this._map.panTo(point);
        this._map.centerAndZoom(point, this._zoom);
    },

    // 自定义控件
    ZoomControl: function () {

        // 默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
        this.defaultOffset = new BMap.Size(10, 10);
    },

    // 移动到指定位置
    panTo: function (location) {
        // console.log(location);
        this._map.panTo(location);
    },

    // 点击事件绑定
    addClickHandler: function (marker, content) {
        var opts = {
            width: 250,     // 信息窗口宽度
            height: 80,     // 信息窗口高度
            // title: "详细信息", // 信息窗口标题
            enableMessage: true//设置允许信息窗发送短息
        };
        // var p = e.target;
        // var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        var infoWindow = new BMap.InfoWindow(content);  // 创建信息窗口对象
        marker.addEventListener("click", function (e) {
            this.openInfoWindow(infoWindow); //开启信息窗口
        })
    },

    // 获取停靠位置
    getAnchor: function (e) {
        switch (e.toUpperCase()) {
            case "TOP_LEFT":
                return BMAP_ANCHOR_TOP_LEFT;
                break;
            case "TOP_RIGHT":
                return BMAP_ANCHOR_TOP_RIGHT;
                break;
            case "BOTTOM_LEFT":
                return BMAP_ANCHOR_BOTTOM_LEFT;
                break;
            case "BOTTOM_RIGHT":
                return BMAP_ANCHOR_BOTTOM_RIGHT;
                break;
        }
    },

    // 获取偏移值
    getOffset: function (e) {
        if (e.indexOf(",") > 0) {
            let size = e.split(",");
            return new BMap.Size(parseInt(size[0]), parseInt(size[1]));
        }
        return null;
    },

    // 获取鼠标绘图工具偏移值
    getZoomOffset: function (e) {
        if (e.indexOf(",") > 0) {
            let size = e.split(",");
            return new BMap.Size(size[0], size[1] + 20);
        }
        return null;
    },

    // 获取地图类型控件样式
    getMapType: function (e) {
        switch (e.toUpperCase()) {
            case "HORIZONTAL":
                return BMAP_MAPTYPE_CONTROL_HORIZONTAL;
                break;
            case "DROPDOWN":
                return BMAP_MAPTYPE_CONTROL_DROPDOWN;
                break;
            case "MAP":
                return BMAP_MAPTYPE_CONTROL_MAP;
                break;
        }
    },

    // 获取地图类型控件样式
    getMapArray: function (e) {
        e = e.split(",");
        let array = [];
        e.forEach(item => {
            switch (item.toUpperCase()) {
                case "NORMAL":
                    array.push(BMAP_NORMAL_MAP);
                    break;
                case "SATELLITE":
                    array.push(BMAP_SATELLITE_MAP);
                    break;
                case "HYBRID":
                    array.push(BMAP_HYBRID_MAP);
                    break;
            }
        });
        return array;
    },

    // 获取平移缩放控件样式
    getNavigationType: function (e) {
        switch (e.toUpperCase()) {
            case "LARGE":
                return BMAP_NAVIGATION_CONTROL_LARGE;
                break;
            case "SMALL":
                return BMAP_NAVIGATION_CONTROL_SMALL;
                break;
            case "PAN":
                return BMAP_NAVIGATION_CONTROL_PAN;
                break;
            case "ZOOM":
                return BMAP_NAVIGATION_CONTROL_ZOOM;
                break;
        }
    },

    // 获取地图类型控件样式
    getModes: function (e) {
        e = e.split(",");
        let array = [];
        e.forEach(item => {
            switch (item.toUpperCase()) {
                case "MARKER":
                    array.push(BMAP_DRAWING_MARKER);
                    break;
                case "CIRCLE":
                    array.push(BMAP_DRAWING_CIRCLE);
                    break;
                case "POLYLINE":
                    array.push(BMAP_DRAWING_POLYLINE);
                    break;
                case "POLYGON":
                    array.push(BMAP_DRAWING_POLYGON);
                    break;
                case "RECTANGLE":
                    array.push(BMAP_DRAWING_RECTANGLE);
                    break;
            }
        });
        return array;
    },
});
